﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using ServiceInterfaces.DataContracts;
using COM;

namespace BLL
{
    public  class OrderBLL
    {

        /// <summary>
        /// 数据库中是否存在该CRC码
        /// </summary>
        /// <param name="crc"></param>
        /// <returns></returns>
        public bool IsExsitCRC(int crc,out int repeatPhotoId)
        {
            repeatPhotoId = 0;
            bool ret = false;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<tb_RepeatCheck> crcList = db.tb_RepeatCheck.ToList();
                tb_RepeatCheck crcMark = crcList.FirstOrDefault(r => r.CrcMark == crc);
                if (crcMark != null)//CRC码已经存在
                {
                    ret = true;
                    repeatPhotoId=crcMark.PhotoId;
                }
                else
                {
                    ret = false;
                }
            }
            return ret;
        }


        /// <summary>
        ///向数据库添加CRC码
        /// </summary>
        /// <param name="crc"></param>
        /// <returns>0添加成功，1添加失败</returns>
        public int AddCRC(int crc ,int photoId)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    tb_RepeatCheck crcIndb = db.tb_RepeatCheck.FirstOrDefault(c=>c.CrcMark ==crc);
                    if (crcIndb == null)
                    {
                        tb_RepeatCheck crcMark = new tb_RepeatCheck()
                        {
                            CrcMark = crc,
                            CreateTime = DateTime.Now,
                            PhotoId = photoId
                        };
                        db.AddTotb_RepeatCheck(crcMark);
                        db.SaveChanges();
                    }
                }
            }
            catch
            {
                ret = 1;
            }
            return ret;
        }

        /// <summary>
        /// 删除CRC码
        /// </summary>
        /// <param name="crc"></param>
        /// <returns>0成功，1失败</returns>
        public int DeleteCRC(int crc)
        {
            int ret = 0;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    tb_RepeatCheck crcMark = db.tb_RepeatCheck.FirstOrDefault(c => c.CrcMark == crc);
                    if (crcMark != null)//存在此crc码
                    {
                        db.DeleteObject(crcMark);
                        db.SaveChanges();
                    }
                }
            }
            catch
            {
                ret = 1;
            }
            return ret;
        }


        /// <summary>
        /// 获得全部商户以及对应所勾选的产品模版
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public Dictionary<int, List<ProductTempleteInfo>> GetAllShopProductTempleteList(string unit)
        {
            Dictionary<int, List<ProductTempleteInfo>> dic = new Dictionary<int, List<ProductTempleteInfo>>();
            List<Shop> shopList = null;
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                shopList = db.Shop.Where(s => s.Status == 1).ToList();
            }

            foreach (var shop in shopList)
            {
                    dic.Add(shop.ShopId, GetProductTempleteList(shop.ShopId, unit));
            }
            return dic;

        }

        /// <summary>
        /// 获取商户所勾选的产品模版
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="unit"></param>
        /// <returns></returns>
        public List<ProductTempleteInfo> GetProductTempleteList(int shopId, string unit)
        {
            List<ProductTempleteInfo> listProductTemplete = new List<ProductTempleteInfo>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop_Product_Price> sppList = db.Shop_Product_Price.Where(s => s.Shop.ShopId == shopId&&s.Tb_Product.Status==1).ToList().OrderByDescending(s=>s.usedTimes).ToList();
                List<Shop_Tech_User> stuList = db.Shop_Tech_User.Where(s => s.ShopId == shopId).ToList();
                List<Shop_Paper_Price> sPaperPriceList = db.Shop_Paper_Price.Where(s => s.ShopId == shopId).ToList();
                foreach (var item in sppList)
                {
                    ServiceInterfaces.DataContracts.Printer_Info printerInfo = null;
                    if (!item.ShopReference.IsLoaded)
                        item.ShopReference.Load();
                    if (!item.Tb_ProductReference.IsLoaded)
                        item.Tb_ProductReference.Load();
                    if (!item.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        item.Tb_Product.Tb_PorductCategoryReference.Load();
                    if (!item.Tb_Product.paperFaceReference.IsLoaded)
                        item.Tb_Product.paperFaceReference.Load();
                    if (!item.Tb_Product.paperTypeReference.IsLoaded)
                        item.Tb_Product.paperTypeReference.Load();
                    if (!item.Tb_Product.Tb_OutShop_ProductCategory.IsLoaded)
                        item.Tb_Product.Tb_OutShop_ProductCategory.Load();
                    if (!item.Tb_Product.printerReference.IsLoaded)
                        item.Tb_Product.printerReference.Load();
                    if (!item.Tb_Product.Tb_FlowTemplate.IsLoaded)
                        item.Tb_Product.Tb_FlowTemplate.Load();
                    if (!item.Tb_Product.tb_ProductTypeReference.IsLoaded)
                        item.Tb_Product.tb_ProductTypeReference.Load();
                    printer printer = item.Tb_Product.printer;
                    if (printer != null)
                    {
                        printerInfo = new ServiceInterfaces.DataContracts.Printer_Info()
                        {
                            PrinterID = item.Tb_Product.printer.PrinterID,
                            PName = item.Tb_Product.printer.PName,
                            PDPI = item.Tb_Product.printer.PDPI
                        };
                    }

                    List<OutProcessShopInfo> OutProcessShopList = new List<OutProcessShopInfo>();//委外商列表
                    foreach (var outshop in item.Tb_Product.Tb_OutShop_ProductCategory)
                    {
                        if (!outshop.OutProcessShopReference.IsLoaded)
                            outshop.OutProcessShopReference.Load();
                        OutProcessShopInfo outshopInfo = new OutProcessShopInfo()
                        {
                            IsDefaultOurProcessShop = outshop.IsDefaultOutShop,//产品默认委外商
                            OutShopId = outshop.OutProcessShop.OutShopId,
                            OutShopName = outshop.OutProcessShop.OutShopName
                        };
                        OutProcessShopList.Add(outshopInfo);
                    }

                    List<WorkOrderFlowListInfo> workflowList = new List<WorkOrderFlowListInfo>();//产品流程

                    foreach (var workflow in item.Tb_Product.Tb_FlowTemplate)
                    {

                        if (!workflow.tb_TechReference.IsLoaded)
                            workflow.tb_TechReference.Load();

                        WorkOrderFlowListInfo workflowInfo = new WorkOrderFlowListInfo()
                        {

                            AssignTime = DateTime.Now,
                            CompletedTime = DateTime.Now,
                            IsEdit = false,
                            ReceiveTime = DateTime.Now,
                            Status = (int)OrderFlowListStatus.Wait,
                            TechId = workflow.tb_Tech.TechId,
                            TechName = workflow.tb_Tech.TechName,
                            UserId = 0,
                            WorkOrder = workflow.WorkOrder,
                            IsNecessery = workflow.IsNecessery,
                            Techtype = workflow.tb_Tech.TechType,
                            IsDesign = workflow.tb_Tech.IsDesign,
                            TechTime = workflow.tb_Tech.NeedTime
                        };

                        #region 商户节点指定操作员
                        Shop_Tech_User stu = stuList.FirstOrDefault(s => s.TechId == workflow.tb_Tech.TechId);
                        if (stu != null)
                        {
                            if (!stu.usersReference.IsLoaded)
                                stu.usersReference.Load();
                            workflowInfo.UserName = stu.users.UserName;
                        }
                        else
                        {
                            workflowInfo.UserName = string.Empty;
                        }

                        workflowList.Add(workflowInfo);
                        #endregion
                    }

                    #region 绑定的节点和附加收费
                    List<TechCommonChargeItemInfo> TechCommonChargeItemInfoList = new List<TechCommonChargeItemInfo>();//绑定好的节点与附加收费
                    List<tb_Tech> techList = db.tb_Tech.ToList();
                    foreach (var tech in techList)
                    {
                        if (!tech.CommonChargeItem.IsLoaded)
                            tech.CommonChargeItem.Load();
                        foreach (var techcomcharge in tech.CommonChargeItem)
                        {
                            TechCommonChargeItemInfo techComChargeInfo = new TechCommonChargeItemInfo()
                            {
                                TechId = tech.TechId,
                                TechName = tech.TechName,
                                CommonChargeItemId = techcomcharge.CommonChargeItemId,
                                CommonChargeItemName = techcomcharge.ItemName
                            };
                            TechCommonChargeItemInfoList.Add(techComChargeInfo);
                        }

                    }
                    #endregion

                    #region 绑定的产品和附加收费
                    List<ProductCommonChargeItemInfo> productCommonChargeItemInfoList = new List<ProductCommonChargeItemInfo>();//绑定好的产品与附加收费
                    if (!item.Tb_Product.CommonChargeItem.IsLoaded)
                        item.Tb_Product.CommonChargeItem.Load();
                    foreach (var comChargeItem in item.Tb_Product.CommonChargeItem)
                    {
                        ProductCommonChargeItemInfo produtcomm = new ProductCommonChargeItemInfo()
                        {
                            CommonChargeItemId = comChargeItem.CommonChargeItemId,
                            CommonChargeItemName = comChargeItem.ItemName,
                            ProductId = item.Tb_Product.ProuctId
                        };
                        productCommonChargeItemInfoList.Add(produtcomm);
                    }
                    #endregion

                    ProductTempleteInfo p = new ProductTempleteInfo()
                    {
                        AppendPrice = item.AppendPrice,
                        Height = item.Tb_Product.Height,
                        PageNum = item.Tb_Product.PageNum,
                        ProductName = item.Tb_Product.ProductName,
                        ProuctId = item.ProductId,
                        UnitPrice = item.UnitPrice,
                        Width = item.Tb_Product.Width,
                        UsedTimes = item.usedTimes == null ? 0 : (int)item.usedTimes,
                        ProductCategoryName = item.Tb_Product.Tb_PorductCategory.ProductCategoryName,
                        ProductCategoryDes = item.Tb_Product.Tb_PorductCategory.ProductCategoryDes,
                        MnemonicCode = item.Tb_Product.mnemonicCode,
                        DefaultPrinter = printerInfo,
                        OutProcessShopList = OutProcessShopList,
                        WorkOrderFlowList = workflowList,
                        ProductTypeCode = item.Tb_Product.tb_ProductType.ProductTypeCode,
                        techCommonChargeItemInfoList = TechCommonChargeItemInfoList,
                        productCommonChargeItemInfoList = productCommonChargeItemInfoList,
                        ProductDes = item.Tb_Product.ProductDes,
                        PaperFaceID = item.Tb_Product.paperFace.PaperFaceID,
                        PaperFaceName =item.Tb_Product.paperFace.Name,
                        PaperTypeID = item.Tb_Product.paperType.PaperTypeID,
                        PaperTypeName =item.Tb_Product.paperType.Name,
                        CoverHeight =item.Tb_Product.CoverHeight,
                        CoverWidth = item.Tb_Product.CoverWidth

                    };
                    
                    #region 产品默认纸型纸面

                    #endregion
                    switch (unit)
                    {
                        case "厘米":

                            p.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(item.Tb_Product.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;
                        case "英寸":
                            p.ProductSize = string.Format("{0}x{1}inch", Math.Round((decimal)item.Tb_Product.Width, 2, MidpointRounding.AwayFromZero), Math.Round((decimal)item.Tb_Product.Height, 2, MidpointRounding.AwayFromZero));
                            break;
                        case "米":
                            p.ProductSize = string.Format("{0}x{1}m", Math.Round((decimal)(item.Tb_Product.Width * 2.54 / 100), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54 / 100), 2, MidpointRounding.AwayFromZero));
                            break;
                        default:
                            p.ProductSize = string.Format("{0}x{1}cm", Math.Round((decimal)(item.Tb_Product.Width * 2.54), 2, MidpointRounding.AwayFromZero), Math.Round((decimal)(item.Tb_Product.Height * 2.54), 2, MidpointRounding.AwayFromZero));
                            break;
                    }
                    listProductTemplete.Add(p);

                }
            }
            return listProductTemplete.OrderByDescending(p => p.UsedTimes).ToList();
        }

        /// <summary>
        /// 获得所有有效商户
        /// </summary>
        /// <returns></returns>
        public List<ShopInfo_Order> GetShopList()
        {
            List<ShopInfo_Order> listShop = new List<ShopInfo_Order>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in db.Shop.Where(s => s.Status == 1).ToList())//"1"表示有效的商户
                {
                    ShopInfo_Order shop = new ShopInfo_Order()
                    {
                        ShopId = item.ShopId,
                        ShopName = item.shopName,
                        MnemonicCode = item.mnemonicCode,
                        PaperFaceId = item.PaperFaceId == null ? 0 : (int)item.PaperFaceId,
                        PaperTypeId = item.PaperTypeId == null ? 0 : (int)item.PaperTypeId
                    };
                    listShop.Add(shop);
                }
            }
            return listShop.OrderBy(s=>s.ShopName).ToList();
        }

        public void MarkOrderBagComplete()
        {
            int delorderinfoStatus=(int)OrderInfoStatus.Deleted;
            int completeOrderinfoStatus=(int)OrderInfoStatus.Completed;
            int stopOrderinfoStatus = (int)OrderInfoStatus.Stop;



            int completeOrderBagStatus=(int)OrderBagStatus.Completed;
            DateTime stTime = DateTime.Now.AddDays(-30);
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int saveflag = 0;



                //处理产品完成的但是订单没有完成的单子
                List<Tb_OrderBag> orderbageCompleteList = db.Tb_OrderBag.Where(b => (b.orderInfo.Where(o => o.status == completeOrderinfoStatus).Count() == b.orderInfo.Count()) && b.Status != completeOrderBagStatus).ToList();
                //orderbageCompleteList.Where(s => s.Status != completeOrderBagStatus).ToList().ForEach(p => p.Status = completeOrderBagStatus);
                foreach (Tb_OrderBag bag in orderbageCompleteList)
                {
                    saveflag++;
                    bag.Status = completeOrderBagStatus;
                    if (saveflag % 10 == 0)
                    {
                        db.SaveChanges();
                    }
                }
                saveflag = 0;
                //处理暂停的单子 实践超过2个月
                DateTime startDate = DateTime.Now.AddMonths(-2);
                List<Tb_OrderBag> orderbageStopList = db.Tb_OrderBag.Where(b => (b.orderInfo.Where(o => o.status == stopOrderinfoStatus).Count() + b.orderInfo.Where(o => o.status == completeOrderinfoStatus).Count()) == b.orderInfo.Count() && b.OrderTime < startDate && b.Status != completeOrderBagStatus).ToList();

                //orderbageStopList.Where(s => s.Status != completeOrderBagStatus).ToList().ForEach(p => p.Status = completeOrderBagStatus);
                //db.SaveChanges();

                foreach (Tb_OrderBag bag in orderbageStopList)
                {
                    saveflag++;
                    bag.Status = completeOrderBagStatus;
                    if (saveflag % 10 == 0)
                    {
                        db.SaveChanges();
                    }
                }

                //处理删除的单子如果已经删除的和正常完成的
                List<Tb_OrderBag> orderbageErrorList = db.Tb_OrderBag.Where(b => (b.orderInfo.Where(o => o.status == delorderinfoStatus).Count() + b.orderInfo.Where(o => o.status == completeOrderinfoStatus).Count()) == b.orderInfo.Count()).ToList();
                List<Tb_OrderBag> listdel = orderbageErrorList.Where(s => s.Status != completeOrderBagStatus).ToList();


                foreach (Tb_OrderBag bag in listdel)
                {
                    saveflag++;
                    bag.Status = completeOrderBagStatus;
                    if (saveflag % 10 == 0)
                    {
                        db.SaveChanges();
                    }
                }

            }

            
        }

        public void CheckOrderInfo()
        {
            int completeOrderinfoStatus = (int)OrderInfoStatus.Completed;
            int productOrderinfoStatus = (int)OrderInfoStatus.Doing;
            int productingWoflStatus = (int)OrderFlowListStatus.Useable;
            
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int userID=db.users.FirstOrDefault().userID;
                //DateTime dateStartDate=DateTime.Now.AddDays(-);
                List<orderInfo> listOrderinfo = db.orderInfo.Where(or => or.status == completeOrderinfoStatus  && or.WorkOrderFlowList.Where(wf => wf.Status == productingWoflStatus).Count() > 0).Take(1000).ToList();
                foreach (orderInfo order in listOrderinfo)
                {
                    Bill_Detail bd = db.Bill_Detail.Where(b=>b.OrderInfoCode==order.OrderProductCode).FirstOrDefault();
                    if (bd == null)
                    {
                        order.status = productOrderinfoStatus;//没打账单的 还原为可以继续生产
                    }
                    else
                    {
                        //打过账单的 停止生产掉
                        order.WorkOrderFlowList.Load();
                        List<WorkOrderFlowList> listWorfl = order.WorkOrderFlowList.Where(w => w.Status != 4).ToList();
                        foreach (WorkOrderFlowList worfl in listWorfl)
                        {
                            worfl.Status = 4;
                            worfl.UserId = userID;
                        }
                    }
                }
                db.SaveChanges();

            }
 
        }
        /// <summary>
        /// 检查已经打过预先打过账单 但是 还没完成的产品
        /// /// </summary>
        public void CheckPrintedOrderInfo()
        {
            int completeOrderinfoStatus = (int)OrderInfoStatus.Completed;
            int productOrderinfoStatus = (int)OrderInfoStatus.Doing;
            int productingWoflStatus = (int)OrderFlowListStatus.Useable;

            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int userID = db.users.FirstOrDefault().userID;
                DateTime dateStartDate = DateTime.Now.AddDays(-15);
                List<orderInfo> listOrderinfo = db.orderInfo.Where(or => or.status == 1 && or.CompleteTime < dateStartDate && or.WorkOrderFlowList.Where(wf => wf.Status == productingWoflStatus).Count() > 0).ToList();
                int icount = 0;
                foreach (orderInfo order in listOrderinfo)
                {
                    icount++;

                    Bill_Detail bd = db.Bill_Detail.Where(b => b.OrderInfoCode == order.OrderProductCode).FirstOrDefault();
                  

                    if (bd == null)
                    {
                        //order.status = productOrderinfoStatus;//没打账单的 还原为可以继续生产
                       
                    }
                    else
                    {
                       
                        //打过账单的 
                        order.WorkOrderFlowList.Load();
                        //打过账单的 检查在理件分队的 是不是完成 如果没完成就吧流程完成并且吧产品也完成
                        List<WorkOrderFlowList> WorflList = db.WorkOrderFlowList.Where(w => (w.tb_Tech.TechType == 7 || w.tb_Tech.TechType == 5) && w.orderInfo.OrderProductId == order.OrderProductId && w.Status != 4).ToList();
                        if (WorflList.Count() > 0)
                        {
                          
                            foreach (WorkOrderFlowList Worfl in WorflList)
                            {

                                Worfl.Status = 4;
                                Worfl.UserId = userID;


                            }
                            order.status = completeOrderinfoStatus;
                        }
                    }
                    db.SaveChanges();
                }


            }

        }
    }
}
